//build: 20240606
//TCP Server
import { tcpServerClass } from './libvbar-m-dxTcpServer.so'
import dxCommon from './dxCommon.js'

const tcpServerObj = new tcpServerClass();
const tcpServer = {}

/**
 * TCP Server Initialization
 * @param {number} port port number
 * @param {number} clientNumber Maximum number of clients
 * @returns true/false
 */
tcpServer.init = function (port, clientNumber, id) {
    let pointer = tcpServerObj.tcpServerInit(port, clientNumber)
    if (!pointer) {
        throw new Error("Tcp Server init failed")
    }
    dxCommon.handleId("tcpServer", id, pointer)
    return true
}
/**
 * TCP Server Data Sending
 * @param {number} clientId Client ID
 * @param {string} data Data to be sent
 * @returns true/false
 */
tcpServer.send = function (clientId, data) {
    return tcpServerObj.tcpServerSend(clientId, data);
}

/**
 * TCP SERVER stop
 * @returns true/false
 */
tcpServer.stop = function (id) {
    let pointer = dxCommon.handleId("tcpServer", id)
    return tcpServerObj.tcpServerStop(pointer)
}

/**
 * TCP SERVER destroy
 * @returns true/false
 */
tcpServer.delete = function (id) {
    let pointer = dxCommon.handleId("tcpServer", id)
    return tcpServerObj.tcpServerDelete(pointer)
}

/**
 * TCP SERVER Scan currently connected clients
 * @returns true/false
 */
tcpServer.scan = function (id) {
    let pointer = dxCommon.handleId("tcpServer", id)
    return tcpServerObj.tcpServerScanClient(pointer)
}

/**
 * TCP SERVER Disconnect the specified client connection based on clientId.
 * @returns true/false
 */
tcpServer.disconnectClient = function (id, clientId) {
    let pointer = dxCommon.handleId("tcpServer", id)
    return tcpServerObj.tcpServerDisconnectClient(pointer, clientId)
}

/**
 * Check if the TCP message queue is empty.
 * @returns true/false
 */
tcpServer.msgIsEmpty = function () {
    return tcpServerObj.msgIsEmpty()
}

/**
 * Read data from the TCP message queue
 * @returns json
 */
tcpServer.msgReceive = function () {
    let msgObj = JSON.parse(tcpServerObj.msgReceive())
    let hexString = msgObj.data;
    var byteString = hexString.match(/.{1,2}/g);
    var byteArray = byteString.map(function(byte) {
        return parseInt(byte, 16);
    });
    var buffer = new Uint8Array(byteArray).buffer;
    msgObj.data = buffer
    return msgObj;
}


export default tcpServer;